import {Shop} from "../shop/shop.actions";
import {Action, State, StateContext} from "@ngxs/store";
import {Injectable} from "@angular/core";
import {Cart} from "./cart.actions";
import * as _ from "lodash";

export interface CartModel {
  list: Shop[]
}

@State<CartModel>({
  name: 'cart',
  defaults: {
    list: []
  }
})
@Injectable({
  providedIn: 'root'
})
export class CartState {

  constructor() {
  }

  @Action(Cart.Add)
  add({patchState, getState}: StateContext<CartModel>, {payload}: Cart.Add) {
    let list: Shop[] = JSON.parse(JSON.stringify(getState().list));
    const idx = _.findIndex(list, s => s.id === payload.id)
    if (idx === -1) {
      list.push(payload)
    } else {
      list[idx] = payload
    }
    patchState({
      list: list
    })
  }

  @Action(Cart.Remove)
  remove({patchState, getState}: StateContext<CartModel>, {id}: Cart.Remove) {
    let list = getState().list;
    list = _.filter(list, s => s.id != id)
    patchState({
      list: list
    })
  }
}
